﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace stringconversions
{
    public class StringConversions
    {
        internal static Dictionary<string, string> CreateDictionary(IEnumerable<Tuple<Parameter, Value>> settings)
        {
            return settings.Aggregate(new Dictionary<string, string>(), (dict, pvPair) =>
                                                                            {
                                                                                dict.Add(pvPair.Item1.Name, pvPair.Item2.Data);
                                                                                return dict;
                                                                            });
        }


        internal static IEnumerable<Tuple<Parameter, Value>> SplitSettingsIntoParamValuePairs(IEnumerable<Setting> settings)
        {
            return settings.Select(s =>
                                       {
                                           var i = s.ParameterValuePair.IndexOf("=");
                                           var paramName = s.ParameterValuePair.Substring(0, i).Trim();
                                           var value = s.ParameterValuePair.Substring(i + 1);
                                           if (paramName == "") throw new ArgumentException("Missing parameter name!");

                                           return new Tuple<Parameter, Value>(new Parameter {Name = paramName},
                                                                              new Value {Data =value});
                                       });
        }


        internal static IEnumerable<Setting> SplitConfigIntoSettings(Configuration config)
        {
            if (config.Settings.Trim() == "") return new Setting[0];
            return config.Settings.Split(';')
                    .Where(s => s.Trim() != "")
                    .Select(s => new Setting {ParameterValuePair = s});
        }


        internal static Dictionary<string, string> ToDictionary(string configuration)
        {
            var settings = SplitConfigIntoSettings(new Configuration {Settings = configuration});
            var pvPairs = SplitSettingsIntoParamValuePairs(settings);
            return CreateDictionary(pvPairs);
        }
    }
}
